package qing.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import qing.entity.Page;

@Component("idao")
public class DaoImpl<T> implements IDao<T> {

	@Autowired
	private SessionFactory sessionFactory;

	private Session getsession() {
		return sessionFactory.getCurrentSession();
	}

	@SuppressWarnings("unchecked")
	@Override
	public T find(Class<T> class1, int id) {
	
		return (T) getsession().get(class1, id);
	}
	

	@Override
	public void create(T basebean) {
		//getsession().save(basebean); //会立刻执行，并返回主键值
		getsession().persist(basebean);
	}

	@Override
	public void update(T basebean) {
		getsession().merge(basebean);  //保存时不比较数据库中是否存在这个对象
		//getsession().update(basebean);
	}

	@Override
	public void delete(T basebean) {
		getsession().delete(basebean);
	}
	
	@Override
	public void delete(Class<T> class1, int id) {
		T t=find(class1, id);
		delete(t);		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> list(String hql) {
		return getsession().createQuery(hql).list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> list(String hql, Object... objects) {
		Query query = createQuery(hql);
		for (int i = 0; objects != null && i < objects.length; i++) {
			query.setParameter(i + 1, objects[i]);
		}
		return query.list();		
	}
	
	@Override
	public int getTotalCount(String hql, Object... objects) {
		Query query = createQuery(hql);
		for (int i = 0; objects != null && i < objects.length; i++) {
			query.setParameter(i + 1, objects[i]);
		}
		Number number = (Number) query.uniqueResult();
		return number.intValue();
	}

	@Override
	public List<T> list(String hql, int firstResult, int maxSize, Object... objects) {
		Query query = createQuery(hql);
		for (int i = 0; objects != null && i < objects.length; i++) {
			query.setParameter(i + 1, objects[i]);
		}
		query.setFirstResult(firstResult).setMaxResults(maxSize);		
		List<T> list=query.list();
		return list;
	}

	@Override
	public Query createQuery(String hql) {
		return getsession().createQuery(hql);
	}

	

}
